package cn.bonoon.kernel.bytecode;

import java.util.List;

import javax.persistence.EntityManager;

import cn.bonoon.entities.ConfigEntity;
import cn.bonoon.kernel.events.BaseEvent;
import cn.bonoon.kernel.exceptions.UniqueCheckException;
/**
 * <pre>
 * 配置文件应该能控制到：
 * 1.全局配置
 * 2.域内配置
 * 3.个人配置
 * </pre>
 * @author jackson
 *
 */
public class ConfigConverter {
	
	protected String configDomain;
	
	public Object get(EntityManager manager, BaseEvent event){
		throw new RuntimeException("不支持对数据库实体的读取操作！");
	}
	
	public void set(EntityManager manager, BaseEvent event){
		throw new RuntimeException("不支持对数据库实体的更新操作！");
	}
	
	/**
	 * 本配置对象所属的域范围，即不同的实体对应一个域范围
	 * @return
	 */
	public String getDomain(){return configDomain;}
	
	protected void uniqueCheck(ConfigHandler event, String key, String value, String msg){
		if(event.exist(key, value)){
			throw new UniqueCheckException(msg, value);
		}
	}
	
	protected void save(ConfigHandler event, List<ConfigEntity> item, String key, String value){
		if(item.isEmpty()){
			event.persist(key, value);
		}else{
			event.merge(item.remove(0), key, value);
		}
	}
	
	protected void remove(EntityManager manager, List<ConfigEntity> item){
		for(ConfigEntity it : item){
			manager.remove(it);
		}
	}
}
